package com.sangcomz.fishbun.util.future;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.concurrent.*;

public class CallableFutureTask<T> extends FutureTask<T> {

    private HiLogLabel TAG = new HiLogLabel(HiLog.ERROR, 0x1234, "CallableFutureTask");

    public CallableFutureTask(Callable<T> callable) {
        super(callable);
    }

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private FutureCallback<T> futureCallback = null;

    public void execute(FutureCallback<T> callback) {
        this.futureCallback = callback;
        if (!isDone()) {
            executorService.submit(this);
        } else {
            try {
                this.futureCallback.onSuccess(get());
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void done() {
        super.done();
        try {
            futureCallback.onSuccess(get());
            HiLog.error(TAG, "Callable future task in done");
        } catch (InterruptedException | ExecutionException | CancellationException e) {
            e.printStackTrace();
        }
    }

    public interface FutureCallback<T> {
        void onSuccess(T result);
    }
}
